package com.stand.hardcode.manager;

import java.util.*;

import javax.jdo.*;

import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import com.stand.hardcode.database.*;
import com.stand.hardcode.entity.*;

public class VirtualShopManager {
	public VirtualShop createShop(String name, String owner) {
		PersistenceManager pm = PMF.get().getPersistenceManager();
		Transaction txn = pm.currentTransaction();
		
		VirtualShop returnShop = null;
		
		try {
			txn.begin();
			
			VirtualShop shop = new VirtualShop();
			shop.setName(name);
			shop.setOwner(owner);
			
			shop = pm.makePersistent(shop);
			
			txn.commit();
			
			returnShop = pm.detachCopy(shop);
		} catch (Exception e) {
			if (txn.isActive())
			{
				txn.rollback();
			}
			
			returnShop = null;
		}
		finally {
			pm.close();
		}
		
		return returnShop;
	}
	
	public List<VirtualShop> getShopsByOwner(String owner) {
		PersistenceManager pm = PMF.get().getPersistenceManager();
		
		List<VirtualShop> returnList = null;

		try {
			Query query = pm.newQuery(VirtualShop.class);
			query.setFilter("owner == ownerParam");
			query.declareParameters("String ownerParam");
			List<VirtualShop> results = (List<VirtualShop>) query.execute(owner);

			results.size();

			returnList = results;
		} catch (Exception e) {
			e.printStackTrace();
			returnList = null;
		} finally {
			pm.close();
		}
		
		return returnList;
	}
	
	public boolean updateVirtualShop(VirtualShop shop) {
		PersistenceManager pm = PMF.get().getPersistenceManager();
		Transaction txn = pm.currentTransaction();
		
		boolean returnVal = false;
		
		try {
			txn.begin();
			
			pm.makePersistent(shop);
			
			txn.commit();
			
			returnVal = true;
		} catch (Exception e) {
			e.printStackTrace();
			if (txn.isActive()) {
				txn.rollback();
			}
			
			returnVal = false;
		} finally {
			pm.close();
		}
		
		return returnVal;
	}
}
